package com.xiubai.appforpda.activitys;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.xiubai.appforpda.R;
import com.xiubai.appforpda.adapter.MainCheckAssetsAdapter;
import com.xiubai.appforpda.db.DatabaseUtils;
import com.xiubai.appforpda.entity.LocationEntity;
import com.xiubai.appforpda.entity.PersonEntity;
import com.xiubai.appforpda.entity.SQLMainPamInventBean;
import com.xiubai.appforpda.entity.SQLPamInvenBean;
import com.xiubai.appforpda.entity.SQLOrgPersonBean;
import com.xiubai.appforpda.entity.SQLOrgStructureBean;
import com.xiubai.appforpda.entity.SQLPamLocationBean;
import com.xiubai.appforpda.entity.SQLPamStatusBean;
import com.xiubai.appforpda.entity.StructureEntity;
import com.xiubai.appforpda.entity.TestBean;
import com.xiubai.appforpda.event.CheckDataChangeEvent;
import com.xiubai.appforpda.jack.lib.AppException;
import com.xiubai.appforpda.jack.lib.net.RequestInformation;
import com.xiubai.appforpda.jack.lib.net.callback.JsonCallback;
import com.xiubai.appforpda.jack.utils.AppConstants;
import com.xiubai.appforpda.jack.utils.Trace;
import com.xiubai.appforpda.jack.utils.UrlHelper;
import com.xiubai.appforpda.utils.ClickUtil;
import com.xiubai.appforpda.utils.DisplayUtil;
import com.xiubai.appforpda.utils.KeyboardUtils;
import com.xiubai.appforpda.utils.ScreenUtils;
import com.xiubai.appforpda.widget.CustomDialog;
import com.xiubai.appforpda.widget.CustomDialogListener;
import com.xiubai.appforpda.widget.DeptDialog;
import com.xiubai.appforpda.widget.LocDialog;
import com.xiubai.appforpda.widget.PersonDialog;
import com.xiubai.appforpda.widget.pull.PullToRefreshView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import static com.xiubai.appforpda.activitys.MainActivity.REQUEST_CAMERA_PERM;
import static com.xiubai.appforpda.activitys.MainActivity.REQUEST_CODE;

public class InnerCheckAssetsActivity extends BaseActivity implements View.OnClickListener, PullToRefreshView.OnRefreshListener {

    private View btn_main_check_back;
    private PullToRefreshView lv_main_check_content;
    MainCheckAssetsAdapter mainCheckAssetsAdapter;
    private CustomDialog cardDialog;
    private int currPage = 0;
    private TextView tv_check_id;
    String bill_code;
    private String result;
    private View btn_continue_scan;
    ArrayList<SQLMainPamInventBean> checkAssetsBeans = new ArrayList<>();
    private boolean is_have = false;
    private SQLMainPamInventBean item;
    private View btn_confirm_check;
    private CustomDialog successDialog;
    private String my_status;
    private boolean disable = false;
    private View btn_check_add;
    private CustomDialog checkAddDialog;
    private EditText et_wuliao_name;
    private EditText et_wuliao_num;
    private HashMap<String, String> loc_list;
    private int check_add_position = -1;
    private String checkAddLocName;
    private String checkCardLocName;
    private HashMap<String, String> name_list;
    private HashMap<String, String> dept_list;
    private HashMap<String, String> status_list;
    private int current_name_position = -1;
    private int current_dept_position = -1;
    private int current_loc_position = -1;
    private int current_status_position = -1;
    private HashMap<String, String> add_loc_list;
    private ArrayList<String> list_name;
    private ArrayList<String> list_dept;
    private ArrayList<String> list_loc;
    private ArrayList<String> list_add;
    private ArrayList<String> list_status;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_check_assets);
        bill_code = getIntent().getStringExtra(AppConstants.BILL_CODE);
        my_status = getIntent().getStringExtra(AppConstants.BILL_STATUS);
        if ("Y".equals(my_status)) {
            disable = true;
        }
        initView();
        initData();
    }

    /**
     *
     */
    private void initData() {
        if (TextUtils.isEmpty(bill_code)) {
            Toast.makeText(this, "没有获取到盘点单号!", Toast.LENGTH_SHORT).show();
            return;
        }
        List<SQLMainPamInventBean> beans = DatabaseUtils.getHelper().queryAll(SQLMainPamInventBean.class);
        if (beans != null) {
            for (SQLMainPamInventBean child : beans) {
                if (bill_code.equals(child.getBillcode())) {
                    child.bill_status = "Y".equals(child.bill_status) ? "Y" : "N";
//                    DatabaseUtils.getHelper().update(SQLMainPamInventBean.class, "billcode", child.getBillcode(), "bill_status", "N");
                    checkAssetsBeans.add(child);
                }
            }

        }
        mainCheckAssetsAdapter = new MainCheckAssetsAdapter(this, checkAssetsBeans);
        lv_main_check_content.setAdapter(mainCheckAssetsAdapter);
        lv_main_check_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//                if (ClickUtil.isFastDoubleClick()) {
//                    return;
//                }
//                SQLMainPamInventBean item = (SQLMainPamInventBean) adapterView.getAdapter().getItem(position);
//                if (item == null) {
//                    return;
//                }
//                showMainCard(item);
            }
        });
        //设置当前上拉加载不可用
        lv_main_check_content.setRefreshAble(true);
        lv_main_check_content.setOnRefreshListener(this);
        //得到真正的listview,我们在给listview设置adapter时或者设置onItemClick事件必须通过它，而不能用lv_main_check_content
        //设置刷新监听器
    }

    @Override
    public void onRefresh(final int which) {
        currPage = which == PullToRefreshView.HEADER ? 1 : ++currPage;
        if (which == PullToRefreshView.HEADER) {
        }
        RequestInformation request = null;
        StringBuilder sb = new StringBuilder(UrlHelper.URL_domain
                + "?page_remove="
                + currPage);
        if (true) {
            lv_main_check_content.onRefreshComplete(PullToRefreshView.HEADER);
            return;
        }
        Trace.d(sb.toString());
        request.setCallback(new JsonCallback<TestBean>() {

            @Override
            public void onCallback(TestBean callback) {
                stopProgressDialog();
                if (callback == null) {
                    currPage--;
                    lv_main_check_content.setVisibility(View.VISIBLE);
                    lv_main_check_content.onRefreshComplete(which, false);
                    lv_main_check_content.enableFooter(false);
                    return;
                }

                if (callback.getStat() == 200) {
                    if (which == PullToRefreshView.HEADER) {
                    }
                    if (which == PullToRefreshView.HEADER) {
                        // 当为第一页时，初始化广告栏
                        lv_main_check_content.onRefreshComplete(which, true);
                        if (which == PullToRefreshView.HEADER) {
                            lv_main_check_content.enableFooter(true);
                        } else {
                            lv_main_check_content.enableFooter(false);
                        }

                        //显示内容为空
                    } else {
                        stopProgressDialog();
                        currPage--;
                        // 因为可能网络恢复，success改为true
                        lv_main_check_content.onRefreshComplete(which, false);
                        lv_main_check_content.enableFooter(false);
                    }
                }
            }

            @Override
            public void onFailure(AppException e) {
                currPage--;
                // 因为可能网络恢复，success改为true
                lv_main_check_content.onRefreshComplete(which, false);
                lv_main_check_content.enableFooter(false);
            }
        }.setReturnType(TestBean.class));

        request.execute();
    }

    private void stopProgressDialog() {

    }

    /**
     * 展现盘点卡片
     *
     * @param item
     */
    private void showMainCard(SQLMainPamInventBean item) {
        this.item = item;

        // todo 将所有盘点后数据置为盘点前数据值,防止盘点后数据为空
        DatabaseUtils.getHelper().update(SQLMainPamInventBean.class, "usercodeh", item.usercodeq, "assetcode=? and billcode=?", new String[]{item.getAssetcode(),bill_code});
        DatabaseUtils.getHelper().update(SQLMainPamInventBean.class, "deptcodeh", item.deptcodeq, "assetcode=? and billcode=?", new String[]{item.getAssetcode(),bill_code});
        DatabaseUtils.getHelper().update(SQLMainPamInventBean.class, "loccodeh", item.loccodeq, "assetcode=? and billcode=?", new String[]{item.getAssetcode(),bill_code});
        DatabaseUtils.getHelper().update(SQLMainPamInventBean.class, "stacodeh", item.stacodeq, "assetcode=? and billcode=?", new String[]{item.getAssetcode(),bill_code});

        showCard();
    }

    /**
     * 显示抓取提示
     */
    private void showCard() {
        cardDialog = new CustomDialog(this, new CustomDialogListener() {
            @Override
            public void onDialogClosed(int closeType) {

            }
        });
        cardDialog.setView(LayoutInflater.from(this).inflate(R.layout.check_assets_card_layout, null));
        View btn_card_confirm = cardDialog.findId(R.id.btn_card_confirm);
        if (btn_card_confirm != null) {
            btn_card_confirm.setOnClickListener(this);
        }
        View btn_card_cancel = cardDialog.findId(R.id.btn_card_cancel);
        if (btn_card_cancel != null) {
            btn_card_cancel.setOnClickListener(this);
        }
        TextView tv_check_id = (TextView) cardDialog.findId(R.id.tv_check_id);
        if (tv_check_id != null) {
            tv_check_id.setText("盘点单号:" + bill_code);
        }
        TextView tv_wuliao_code = (TextView) cardDialog.findId(R.id.tv_wuliao_code);
        if (tv_wuliao_code != null) {
            tv_wuliao_code.setText(item.getAssetcode());
        }
        TextView tv_name = (TextView) cardDialog.findId(R.id.tv_name);
        if (tv_name != null) {
            tv_name.setText("经办人: " + AppConstants.USER_NAME);
        }
        TextView tv_wuliao_name = (TextView) cardDialog.findId(R.id.tv_wuliao_name);
        if (tv_wuliao_name != null) {
            tv_wuliao_name.setText(item.getAssetname());
        }

        initPersonDialog();

        initDeptDialog();

        initLocDialog();

        Spinner sp_status = (Spinner) cardDialog.findId(R.id.sp_status);
        if (sp_status != null) {
            initSpinnerStatusData(sp_status);
            sp_status.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                    Trace.d("select position " + position);

                    String str;
                    str = (String) adapterView.getAdapter().getItem(position);
                    current_status_position = list_status.indexOf(str);
                    String staa = null;
                    for (String code : status_list.keySet()) {
                        if (str.equals(status_list.get(code))) {
                            staa = code;
                            break;
                        }
                    }
                    DatabaseUtils.getHelper().update(SQLMainPamInventBean.class, "stacodeh", staa, "assetcode=? and billcode=?", new String[]{item.getAssetcode(),bill_code});
                    item.stacodeh = staa;
                    mainCheckAssetsAdapter.notifyDataSetChanged();
                }

                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });

        }

        cardDialog.setCanceledOutside(false);
        cardDialog.setCancelable(false);
        cardDialog.show();

        dialogWindow(cardDialog);
    }

    private void initPersonDialog() {
        final TextView txt_person_name = (TextView)cardDialog.findId(R.id.sp_user);
        final List<SQLOrgPersonBean> personBeans = DatabaseUtils.getHelper().queryAll(SQLOrgPersonBean.class);
        String defaultCode = "";
        for(SQLOrgPersonBean bean :personBeans){
            if(item.usercodeh.equals("")){
                if(bean.psncode.equals(item.usercodeq)){
                    txt_person_name.setText(bean.psnname+"");
                    defaultCode = item.usercodeq;
                }
            }else {
                if (bean.psncode.equals(item.usercodeh)) {
                    txt_person_name.setText(bean.psnname + "");
                    defaultCode = item.usercodeh;
                }
            }

        }
        final String defaultCode1 = defaultCode;
        txt_person_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PersonDialog.OnCheckedListener onCheckedListener = new PersonDialog.OnCheckedListener() {
                    @Override
                    public void onCheck(PersonEntity entity) {
                        Trace.d("select position " + entity.psnname);
                        txt_person_name.setText(entity.psnname+"");
                        String staa = entity.psncode;
                        DatabaseUtils.getHelper().update(SQLMainPamInventBean.class, "usercodeh", staa, "assetcode=? and billcode=?", new String[]{item.getAssetcode(),bill_code});
                        item.usercodeh = staa;
                        mainCheckAssetsAdapter.notifyDataSetChanged();
                    }
                };
                PersonDialog locDialog = new PersonDialog(InnerCheckAssetsActivity.this,defaultCode1,personBeans, onCheckedListener);
                locDialog.show();
            }
        });
    }

    private void initDeptDialog() {
        final TextView txt_dept_name = (TextView)cardDialog.findId(R.id.sp_dept_name);
        final List<SQLOrgStructureBean> beans = DatabaseUtils.getHelper().queryAll(SQLOrgStructureBean.class);
        String defaultCode = "";
        for(SQLOrgStructureBean bean :beans){
            if(item.deptcodeh.equals("")){
                if(bean.deptcode.equals(item.deptcodeq)){
                    txt_dept_name.setText(bean.deptname+"");
                    defaultCode = item.deptcodeq;
                }
            }else {
                if (bean.deptcode.equals(item.deptcodeh)) {
                    txt_dept_name.setText(bean.deptname + "");
                    defaultCode = item.deptcodeh;
                }
            }

        }
        final String defaultCode1 = defaultCode;
        txt_dept_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DeptDialog.OnCheckedListener onCheckedListener = new DeptDialog.OnCheckedListener() {
                    @Override
                    public void onCheck(StructureEntity entity) {
                        Trace.d("select position " + entity.deptname);
                        txt_dept_name.setText(entity.deptname+"");
                        String staa = entity.deptcode;
                        DatabaseUtils.getHelper().update(SQLMainPamInventBean.class, "deptcodeh", staa, "assetcode=? and billcode=?", new String[]{item.getAssetcode(),bill_code});
                        item.deptcodeh = staa;
                        mainCheckAssetsAdapter.notifyDataSetChanged();
                    }
                };
                DeptDialog deptDialog = new DeptDialog(InnerCheckAssetsActivity.this,defaultCode1,beans, onCheckedListener);
                deptDialog.show();
            }
        });
    }

    private void initLocDialog() {
        final TextView txt_loc_name = (TextView)cardDialog.findId(R.id.sp_location);
        final List<SQLPamLocationBean> locBeans = DatabaseUtils.getHelper().queryAll(SQLPamLocationBean.class);
        String defaultLocCode = "";
        for(SQLPamLocationBean bean :locBeans){
            if(item.loccodeh.equals("")){
                if(bean.loccode.equals(item.loccodeq)){
                    txt_loc_name.setText(bean.locname+"");
                    defaultLocCode = item.loccodeq;
                }
            }else {
                if (bean.loccode.equals(item.loccodeh)) {
                    txt_loc_name.setText(bean.locname + "");
                    defaultLocCode = item.loccodeh;
                }
            }

        }
        final String defaultLocCode1 = defaultLocCode;
        txt_loc_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LocDialog.OnCheckedListener onCheckedListener = new LocDialog.OnCheckedListener() {
                    @Override
                    public void onCheck(LocationEntity entity) {
                        Trace.d("select position " + entity.locname);
                        txt_loc_name.setText(entity.locname+"");
                        String staa = entity.loccode;
                        DatabaseUtils.getHelper().update(SQLMainPamInventBean.class, "loccodeh", staa, "assetcode=? and billcode=?", new String[]{item.getAssetcode(),bill_code});
                        item.loccodeh = staa;
                        mainCheckAssetsAdapter.notifyDataSetChanged();
                    }
                };
                LocDialog locDialog = new LocDialog(InnerCheckAssetsActivity.this,defaultLocCode1,locBeans, onCheckedListener);
                locDialog.show();
            }
        });
    }

    /**
     * 状态
     *
     * @param sp
     */
    private void initSpinnerStatusData(Spinner sp) {
        //数据
        if (status_list == null) {
            status_list = new HashMap<>();
        }
        if (status_list.isEmpty()) {
            List<SQLPamStatusBean> beans = DatabaseUtils.getHelper().queryAll(SQLPamStatusBean.class);
            if (beans != null) {
                for (SQLPamStatusBean child : beans) {
                    status_list.put(child.stacode, child.staname);
                }
            }
        }
        list_status = new ArrayList<>();
        String current = null;
        for (String key : status_list.keySet()) {
            list_status.add(status_list.get(key));
        }
        String current_dept = status_list.get(TextUtils.isEmpty(item.stacodeh) ? item.stacodeq : item.stacodeh);
        //适配器
        ArrayAdapter<String> arr_adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list_status);
        //设置样式
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        sp.setAdapter(arr_adapter);
        if (current_dept != null)
            current_status_position = list_status.indexOf(current_dept);
        sp.setSelection(current_status_position == -1 ? 0 : current_status_position, true);

    }

    /**
     * weizhi
     *
     * @param sp
     */
    private void initSpinnerLocationData(Spinner sp) {
        //数据
        if (loc_list == null) {
            loc_list = new HashMap<>();
        }
        if (loc_list.isEmpty()) {
            List<SQLPamLocationBean> beans = DatabaseUtils.getHelper().queryAll(SQLPamLocationBean.class);
            if (beans != null) {
                for (SQLPamLocationBean child : beans) {
                    loc_list.put(child.loccode, child.locname);
                }
            }
        }
        list_loc = new ArrayList<>();
        String current = null;
        for (String key : loc_list.keySet()) {
            list_loc.add(loc_list.get(key));
        }
        String current_dept = loc_list.get(TextUtils.isEmpty(item.loccodeh) ? item.loccodeq : item.loccodeh);
        //适配器
        ArrayAdapter<String> arr_adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list_loc);
        //设置样式
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        sp.setAdapter(arr_adapter);
        if (current_dept != null)
            current_loc_position = list_loc.indexOf(current_dept);

        sp.setSelection(current_loc_position == -1 ? 0 : current_loc_position, true);

    }

    /**
     * 部门
     *
     * @param sp
     */
    private void initSpinnerDeptData(Spinner sp) {
//数据
        if (dept_list == null) {
            dept_list = new HashMap<>();
        }
        if (dept_list.isEmpty()) {
            List<SQLOrgStructureBean> beans = DatabaseUtils.getHelper().queryAll(SQLOrgStructureBean.class);
            if (beans != null) {
                for (SQLOrgStructureBean child : beans) {
                    dept_list.put(child.deptcode, child.deptname);
                }
            }
        }
        list_dept = new ArrayList<>();
        String current = null;
        for (String key : dept_list.keySet()) {
            list_dept.add(dept_list.get(key));
        }
        String current_dept = dept_list.get(TextUtils.isEmpty(item.deptcodeh) ? item.deptcodeq : item.deptcodeh);
        //适配器
        ArrayAdapter<String> arr_adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list_dept);
        //设置样式
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        sp.setAdapter(arr_adapter);
        if (current_dept != null)
            current_dept_position = list_dept.indexOf(current_dept);

        sp.setSelection(current_dept_position == -1 ? 0 : current_dept_position, true);


    }

    /**
     * 用户
     *
     * @param sp
     */
    private void initSpinnerData(Spinner sp) {
        //数据
        if (name_list == null) {
            name_list = new HashMap<>();
        }
        if (name_list.isEmpty()) {
            List<SQLOrgPersonBean> orgPersonBeans = DatabaseUtils.getHelper().queryAll(SQLOrgPersonBean.class);
            if (orgPersonBeans != null) {
                for (SQLOrgPersonBean orgPersonBean : orgPersonBeans) {
                    name_list.put(orgPersonBean.psncode, orgPersonBean.psnname);
                }
            }
        }
        list_name = new ArrayList<>();
        String current = null;
        for (String key : name_list.keySet()) {
            list_name.add(name_list.get(key));
        }

        String current_name;
        current_name = name_list.get(TextUtils.isEmpty(item.usercodeh) ? item.usercodeq : item.usercodeh);
        //适配器
        ArrayAdapter<String> arr_adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list_name);
        //设置样式
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        sp.setAdapter(arr_adapter);
        current_name_position = list_name.indexOf(current_name);
        sp.setSelection(current_name_position == -1 ? 0 : current_name_position, true);

    }

    /**
     * weizhi
     *
     * @param sp
     */
    private void initLocationData(Spinner sp) {
        add_loc_list = new HashMap<>();
        List<SQLPamLocationBean> beans = DatabaseUtils.getHelper().queryAll(SQLPamLocationBean.class);
        if (beans != null) {
            for (SQLPamLocationBean child : beans) {
                add_loc_list.put(child.loccode, child.locname);
            }
        }
        //适配器
        list_add = new ArrayList<>();
        for (String key : add_loc_list.keySet()) {
            list_add.add(add_loc_list.get(key));
        }
        ArrayAdapter<String> arr_adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list_add);
        //设置样式
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        sp.setAdapter(arr_adapter);
    }

    private void dialogWindow(Dialog dialog) {
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);

        WindowManager.LayoutParams lp = window.getAttributes();
        int screenWidth = ScreenUtils.getScreenWidth(this);
//        PixelDpHelper.dip2px(this, )
        lp.width = (int) (screenWidth * 0.90f);
//        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
    }


    private void initView() {
        TextView tv_name = (TextView) findViewById(R.id.tv_name);
        tv_name.setText("经办人: " + AppConstants.USER_NAME);
        tv_check_id = (TextView) findViewById(R.id.tv_check_id);
        tv_check_id.setText("盘点单号:" + bill_code);
        lv_main_check_content = (PullToRefreshView) findViewById(R.id.lv_main_check_content);
        btn_main_check_back = findViewById(R.id.btn_main_check_back);
        btn_main_check_back.setOnClickListener(this);
        btn_continue_scan = findViewById(R.id.btn_continue_scan);
        btn_continue_scan.setOnClickListener(this);
        btn_confirm_check = findViewById(R.id.btn_confirm_check);
        btn_confirm_check.setOnClickListener(this);
        btn_check_add = findViewById(R.id.btn_check_add);
        btn_check_add.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (ClickUtil.isFastDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_check_add:
                showCheckAdd();
                break;
            case R.id.btn_main_check_back:
                finish();
                break;
            case R.id.btn_card_confirm:
                if (null != item) {
                    item.bill_status = "Y";
                    DatabaseUtils.getHelper().update(SQLMainPamInventBean.class, "assetcode", item.getAssetcode(), "bill_status", "Y");
                    for (SQLMainPamInventBean bean : checkAssetsBeans) {
                        if (item.getAssetcode().equals(bean.getAssetcode())) {
                            bean.bill_status = "Y";
                            mainCheckAssetsAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                }
                dismissCardView();
                break;
            case R.id.btn_add_confirm:
                if (et_wuliao_name != null && et_wuliao_num != null) {
                    String name = et_wuliao_name.getText().toString();
                    String num = et_wuliao_num.getText().toString();
                    if (TextUtils.isEmpty(name) || TextUtils.isEmpty(num)) {
                        Toast.makeText(this, "资产名称或数量不能为空!", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        // do something
                        SQLMainPamInventBean sqlMainPamInventBean = new SQLMainPamInventBean();
                        sqlMainPamInventBean.assetname = name;
                        sqlMainPamInventBean.pamsum = num;
                        sqlMainPamInventBean.loccodeq = checkAddLocName;
                        sqlMainPamInventBean.bill_status = "Y";
                        sqlMainPamInventBean.my_status = "Y";
                        sqlMainPamInventBean.billcode = bill_code;

                        DatabaseUtils.getHelper().save(sqlMainPamInventBean);
                        // 将盘盈数据添加到集合,盘点结束时统一更改 操作人等信息
                        checkAssetsBeans.add(sqlMainPamInventBean);
                        mainCheckAssetsAdapter.notifyDataSetChanged();
                    }

                } else {
                    dialogDismiss(checkAddDialog);
                    return;
                }
                /*if (null != item) {
                    item.bill_status = "Y";
                    DatabaseUtils.getHelper().update(SQLMainPamInventBean.class, "assetcode", item.getAssetcode(), "bill_status", "Y");
                    for (SQLMainPamInventBean bean : checkAssetsBeans) {
                        if (item.getAssetcode().equals(bean.getAssetcode())) {
                            bean.bill_status = "Y";
                            mainCheckAssetsAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                }*/
                dialogDismiss(checkAddDialog);
                break;
            case R.id.btn_add_cancel:
                dialogDismiss(checkAddDialog);
                break;
            case R.id.btn_card_cancel:
                dialogDismiss(cardDialog);
                break;
            case R.id.btn_confirm_check:
                showSuccessDialog("确认盘点结束?", "确认", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        List<SQLPamInvenBean> list = DatabaseUtils.getHelper().queryByArgs(SQLPamInvenBean.class, "billcode", bill_code);
                        if (null != list) {
                            DatabaseUtils.getHelper().update(SQLPamInvenBean.class, "billcode", bill_code, "my_status", "Y");
                        }
                        for (SQLMainPamInventBean bean : checkAssetsBeans) {
                            DatabaseUtils.getHelper().update(SQLMainPamInventBean.class, "assetcode", bean.getAssetcode(), "my_status", "Y");
                            DatabaseUtils.getHelper().update(SQLMainPamInventBean.class, "assetcode", bean.getAssetcode(), "operator", AppConstants.USER_CODE);
                        }
                        EventBus.getDefault().post(new CheckDataChangeEvent(bill_code));
                        dialogDismiss(successDialog);
                        finish();
                    }
                });
                break;
            case R.id.btn_continue_scan:
                if (disable) {
                    Toast.makeText(this, "盘点已经确认结束!", Toast.LENGTH_SHORT).show();
                    return;
                }
                startScan();
                break;
            case R.id.btn_data_return:
                dialogDismiss(successDialog);
                break;
        }
    }

    /**
     * 显示盘盈的对话框
     */
    private void showCheckAdd() {
        checkAddDialog = new CustomDialog(this, new CustomDialogListener() {
            @Override
            public void onDialogClosed(int closeType) {

            }
        });
        checkAddDialog.setView(LayoutInflater.from(this).inflate(R.layout.check_add_layout, null));
        et_wuliao_name = (EditText) checkAddDialog.findId(R.id.et_wuliao_name);
        et_wuliao_num = (EditText) checkAddDialog.findId(R.id.et_wuliao_num);
        TextView tv_check_id = (TextView) checkAddDialog.findId(R.id.tv_check_id);
        TextView tv_name = (TextView)checkAddDialog.findId(R.id.tv_name);
        if(tv_name != null){
            tv_name.setText("经办人:"+AppConstants.USER_NAME);
        }
        if (tv_check_id != null) {
            tv_check_id.setText("盘点单号:" + bill_code);
        }


        final TextView txt_loc_name = (TextView)checkAddDialog.findId(R.id.sp_location);
        final List<SQLPamLocationBean> locBeans = DatabaseUtils.getHelper().queryAll(SQLPamLocationBean.class);
        final String defaultLocCode1 = "";
        txt_loc_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LocDialog.OnCheckedListener onCheckedListener = new LocDialog.OnCheckedListener() {
                    @Override
                    public void onCheck(LocationEntity entity) {
                        txt_loc_name.setText(entity.locname+"");
                        checkAddLocName = entity.loccode;

                    }
                };
                LocDialog locDialog = new LocDialog(InnerCheckAssetsActivity.this,defaultLocCode1,locBeans, onCheckedListener);
                locDialog.show();
            }
        });


        /*Spinner sp_location = (Spinner) checkAddDialog.findId(R.id.sp_location);
        if (sp_location != null) {
            initLocationData(sp_location);
            sp_location.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                    Trace.d("select position " + position);
                    checkAddLocName = (String) adapterView.getAdapter().getItem(position);
                }

                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });
            sp_location.setSelection(0);
        }*/

        View btn_card_add_confirm = checkAddDialog.findId(R.id.btn_add_confirm);
        if (btn_card_add_confirm != null) {
            btn_card_add_confirm.setOnClickListener(this);
        }
        View btn_card_cancel = checkAddDialog.findId(R.id.btn_add_cancel);
        if (btn_card_cancel != null) {
            btn_card_cancel.setOnClickListener(this);
        }
        checkAddDialog.show();

        dialogWindow(checkAddDialog);
    }

    private void initLocAddDialog() {

    }


    private void dialogDismiss(Dialog dialog) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    private void dismissCardView() {
        if (cardDialog != null && cardDialog.isShowing()) {
            cardDialog.dismiss();
            KeyboardUtils.hideSoftInput(this);
        }
    }

    private void startScan() {
        Intent intent4 = new Intent(InnerCheckAssetsActivity.this, CaptureActivity.class);
        startActivityForResult(intent4, REQUEST_CODE);
    }


    /**
     * 显示抓取成功
     */
    private void showSuccessDialog(String message, String buttonName, View.OnClickListener listener) {
        successDialog = new CustomDialog(this, new CustomDialogListener() {
            @Override
            public void onDialogClosed(int closeType) {

            }
        });
        successDialog.setView(LayoutInflater.from(this).inflate(R.layout.single_button_layout, null));
        TextView tv_input = (TextView) successDialog.findId(R.id.tv_single_message);
        TextView btn_data_confirm = (TextView) successDialog.findId(R.id.btn_data_confirm);
        View btn_data_return = successDialog.findId(R.id.btn_data_return);
        if (btn_data_return != null) {
            btn_data_return.setVisibility(View.VISIBLE);
            btn_data_return.setOnClickListener(this);
        }
        if (btn_data_confirm != null) {
            btn_data_confirm.setText(buttonName);
            btn_data_confirm.setOnClickListener(listener);
        }
        if (tv_input != null) {
            tv_input.setText(message);
        }
        successDialog.show();

        dialogMatchWindow(successDialog);
    }

    private void dialogMatchWindow(Dialog dialog) {
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);

        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = DisplayUtil.dip2px(300, this.getResources().getDisplayMetrics().density);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    result = bundle.getString(CodeUtils.RESULT_STRING);
                    Trace.d("result" + result);
//                    Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show();
                    initPromt();
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(InnerCheckAssetsActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_BACK) {
                    Trace.d("stop");
                }
            }
        } else if (requestCode == REQUEST_CAMERA_PERM) {
            Toast.makeText(this, "从设置页面返回...", Toast.LENGTH_SHORT)
                    .show();
        }
    }

    private void initPromt() {
        if (TextUtils.isEmpty(result)) {
            Toast.makeText(this, "扫描失败!", Toast.LENGTH_SHORT).show();
            return;
        }
        is_have = false;
        for (SQLMainPamInventBean bean : checkAssetsBeans) {
            if (result.equals(bean.getAssetcode())) {
                showMainCard(bean);
                is_have = true;
                break;
            }
        }
        if (!is_have) {
            Toast.makeText(this, "没有找到匹配的资产编码", Toast.LENGTH_SHORT).show();
        }
    }
}
